﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbouiCOM;
using BoAddonBiz_FreightForwarder.BusinessBase;

namespace BoAddonBiz_FreightForwarder
{
    /// <summary>
    /// 主单领用
    /// </summary>
    [ControlB1Form(IsNew = true, FormType = B1FormTypes.ado_AVA_FF_AirOrderUsed)]
    class B1Form_AirOrderUsed : SAPBoAddon.B1Form
    {
        public B1Form_AirOrderUsed()
        {
            this.frm_MenuEvent += new SAPBoAddon.IB1FormEvents.B1MenuEventEventHandler(B1Form_AirOrderUsed_frm_MenuEvent);
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_AirOrderUsed_frm_ChooseFormListEvent);
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_AirOrderUsed_frm_ItemEvent);
            this.frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(B1Form_AirOrderUsed_frm_FormDataEvent);
        }
        #region 基础基类
        protected override bool BeforeSaveCheckFormData()
        {
            string OrderNum = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "9").ToString().Trim();
            if (string.IsNullOrEmpty(OrderNum))
            {
                SBOApp.StatusBar.SetText("[主单号] 缺失，请填写.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Error);
                return false;
            }
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = "AVA_FF_AirOrderUsed";
            FormSetting.FormFileName = "AVA_FF_AirOrderUsedForm.srf";
            #region 控件是否可编辑
            FormSetting.FormModeSetting.itmNewModeDisable = new string[] { "3", "7", "61", "63", "29" };

            FormSetting.FormModeSetting.StatusItemUID = "7";
            SAPBoAddon.BrowseModeSetting ModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            ModeSetting.Status = "P";
            ModeSetting.itmBrowseModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "3", "61", "63" });
            ModeSetting.itmBrowseModeDisable = new string[] { "3", "61", "63" };

            ModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            ModeSetting.Status = "S";
            ModeSetting.itmBrowseModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, new string[] { "3", "61", "63" });
            ModeSetting.itmBrowseModeDisable = new string[] { "3", "61", "63" };

            ModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            ModeSetting.Status = "C";
            ModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument);

            FormSetting.FormModeSetting.itmFindModeEnable = new string[] { "3", "7", "61", "63", "29" };
            #endregion
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {

        }
        #endregion

        #region 事件处理
        void B1Form_AirOrderUsed_frm_FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {

            }
            else
            {
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_ADD && pVal.ActionSuccess)
                {
                    this.AirOrderUsed();/*更新领用的主单  状态[R]、使用次数+1*/
                }
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE && pVal.ActionSuccess)
                {
                    this.CloseAirOrderUse();/*by WangPeng 2012年9月17日 18:34:59*/
                }
            }
        }

        void B1Form_AirOrderUsed_frm_MenuEvent(SAPBoAddon.B1AddonBase.B1MenuEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {

            }
            else
            {
                if (pVal.MenuUID == B1MenuTypes.ado_SYS_Add)
                {
                    SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "61", DateTime.Now.ToString("yyyyMMdd").ToString());
                    SAPBoAddon.B1Assistant.Item.SetValue(CurrentForm, "63", Utils.GetCurrentUser().Operator);
                }
            }
        }

        void B1Form_AirOrderUsed_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");
            if (pVal.Before_Action)
            {
                SAPbouiCOM.ChooseFromList cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                SAPbouiCOM.Conditions cons;
                SAPbouiCOM.Condition con;
                switch (pVal.ChooseFromListUID)
                {
                    case "cfl_AirOrder":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "U_Status";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_NOT_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    //case "cfl_OCRD_C":
                    //    cons = new SAPbouiCOM.Conditions();
                    //    con = cons.Add();
                    //    con.Alias = "CardType";
                    //    con.CondVal = "S";
                    //    con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                    //    cfl.SetConditions(cons);
                    //    break;
                }
            }
            else
            {
                if (pVal.Action_Success)
                {
                    /*航空公司*/
                    if (pVal.ChooseFromListUID == "CFL_AirLine")
                    {
                        dbds.SetValue("U_AirlineCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_AirLineCode", 0).ToString());
                        dbds.SetValue("U_Airline", dbds.Offset, pVal.SelectedObjects.GetValue("U_AirLineName", 0).ToString());
                    }
                    if (pVal.ChooseFromListUID == "cfl_OCRD_C")
                    {
                        dbds.SetValue("U_Company", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dbds.SetValue("U_CompanyC", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_Contact", dbds.Offset, Cntct.FullName);
                            dbds.SetValue("U_CntctMethod", dbds.Offset, Cntct.Cellolar);
                        }
                    }
                    if (pVal.ChooseFromListUID == "cfl_PORT")
                    {
                        dbds.SetValue("U_PortCode", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0).ToString());
                        /*港口三字码*/
                        dbds.SetValue("U_DestinationPortC", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        /*港口名称  取 港口外文名称*/
                        dbds.SetValue("U_DestinationPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString());
                    }
                    if (pVal.ChooseFromListUID == "cfl_AirOrder")
                    {
                        dbds.SetValue("U_OrderNumber", dbds.Offset, string.Format("{0}-{1}", pVal.SelectedObjects.GetValue("U_AirlineCode", 0), pVal.SelectedObjects.GetValue("U_OrderNumber", 0)));
                        //dbds.SetValue("U_PortCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0));
                        //dbds.SetValue("U_DestinationPortC", dbds.Offset, pVal.SelectedObjects.GetValue("U_DestinationPortC", 0));
                        //dbds.SetValue("U_DestinationPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_DestinationPort", 0));
                        dbds.SetValue("U_AirlineCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_AirlineCode", 0));
                        dbds.SetValue("U_Airline", dbds.Offset, pVal.SelectedObjects.GetValue("U_Airline", 0));
                        dbds.SetValue("U_AirOrderEntry", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0));
                    }
                }
            }
        }

        void B1Form_AirOrderUsed_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "1" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    //判断主单号是否在在
                    AirOrderExists();
                    this.ConformCloseDate(ref BubbleEvent);/*确认 航空公司结算日期 by WangPeng 2012年9月17日 18:34:19*/
                }
                if (pVal.ItemUID == "27" && pVal.EventType == BoEventTypes.et_CLICK)// 添加、查找 状态 不允许选中
                {
                    if (this.CurrentForm.Mode == BoFormMode.fm_OK_MODE || this.CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE)
                    {

                    }
                    else
                    {
                        BubbleEvent = false;
                        SBOApp.StatusBar.SetText("作废无效.", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                    }
                }
                if (pVal.ItemUID == "btn_Send" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    this.CheckAirOrdervalid(ref BubbleEvent);
                }
            }
            else
            {
                if (new string[] { "45" }.Contains<string>(pVal.ItemUID) && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, "AVA_FF_Port");
                }
                if (new string[] { "46" }.Contains<string>(pVal.ItemUID) && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, "AVA_FF_AirOrder");
                }
                if (pVal.ItemUID == "27" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED && pVal.ActionSuccess)
                {
                    SetItemsEnableInNullify();
                }
                if (pVal.ItemUID == "btn_Send" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    this.ChangeOrderStatus();
                }
                if (pVal.ItemUID == "37" && pVal.EventType == BoEventTypes.et_VALIDATE)
                {
                    if (!string.IsNullOrEmpty(SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, pVal.ItemUID).ToString().Trim()))
                    {
                        SBOApp.MessageBox("请确认 [航空公司结算日期] ,更新之后将关闭该主单领用.");
                    }
                }
                if (pVal.ItemUID == "btn_CrtBP" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    this.CopytoBusinessOperation();
                }
            }
        }
        #endregion

        #region 功能函数
        /// <summary>
        /// 设置相关控件在作废下的编辑情况
        /// </summary>
        /// <author>WangPeng</author>
        private void SetItemsEnableInNullify()
        {
            if (this.CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE || this.CurrentForm.Mode == BoFormMode.fm_OK_MODE)
            {
                SAPbouiCOM.CheckBox oChBox = (SAPbouiCOM.CheckBox)this.CurrentForm.Items.Item("27").Specific;
                bool IsEnable = oChBox.Checked;  /*如果在et_CLICK事件下 每次的取值都是与页面显示的相反 By WangPeng 2012年9月14日 16:10:31*/
                SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, "29", IsEnable);
            }
        }
        /// <summary>
        /// 主单是否存在
        /// </summary>
        /// <param name="FormUID"></param>
        private void AirOrderExists()
        {
            SAPbobsCOM.Recordset ors;
            string AirOrder = string.Empty;
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

            if (CurrentForm.Mode == BoFormMode.fm_ADD_MODE || CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE)
            {
                AirOrder = SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "9").ToString();
                if (string.IsNullOrEmpty(AirOrder))
                {
                    //SBOApp.MessageBox("单据保存时主单号不能为空，请检查！");
                    //return;
                    throw new Exception("单据保存时主单号不能为空，请检查！");
                }
                string SQL_Check = string.Format("SELECT Count(1) FROM [@AVA_FF_OAOD] Where U_AirlineCode+N'-'+U_OrderNumber = N'{0}' ", AirOrder);
                ors.DoQuery(SQL_Check);
                if (ors.Fields.Item(0).Value <= 0)
                {
                    //SBOApp.MessageBox("您录入的主单号：" + AirOrder + " 在系统中不存在，请检查！");
                    //return;
                    throw new Exception("您录入的主单号：" + AirOrder + " 在系统中不存在，请检查！");
                }
            }
        }
        /// <summary>
        /// 更新主单号的状态
        /// </summary>
        /// <author>WangPeng</author>
        private void AirOrderUsed()
        {
            SAPbouiCOM.DBDataSource dbds_OAOU = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            string Docentry_AirOrder = dbds_OAOU.GetValue("U_AirOrderEntry", dbds_OAOU.Offset).Trim();
            if (string.IsNullOrEmpty(Docentry_AirOrder))
            {
                throw new Exception("主单领用数据异常.");
            }
            string SQL_setAirOrderStatus = string.Format("UPDATE [@AVA_FF_OAOD] SET U_Status = N'R' ,U_UseCount =ISNULL(U_UseCount,0) + 1 Where DocEntry={0}", Docentry_AirOrder);
            oRst.DoQuery(SQL_setAirOrderStatus);
        }

        /// <summary>
        /// 必填字段验证
        /// </summary>
        /// <author>WangPeng</author>
        private void CheckAirOrdervalid(ref bool BubbleEvent)
        {
            if (this.CurrentForm.Mode != BoFormMode.fm_OK_MODE)
            {
                SBOApp.StatusBar.SetText("请先保存数据.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Error);
                BubbleEvent = false;
                return;
            }
            SAPbouiCOM.DBDataSource dbds_OAOU = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            string[] Fields_MustUse = new string[] { "U_OrderNumber", "U_DestinationPortC", "U_Contact" };
            string Val = string.Empty;
            foreach (var FieldName in Fields_MustUse)
            {
                Val = dbds_OAOU.GetValue(FieldName, dbds_OAOU.Offset).Trim();
                if (string.IsNullOrEmpty(Val))
                {
                    oRst.DoQuery(string.Format("SELECT Descr FROM [CUFD] WHERE TableID=N'@AVA_FF_OAOU' AND AliasID=N'{0}' ", FieldName.Substring(2)));
                    SBOApp.StatusBar.SetText(string.Format("{0} 缺失，请填写...", oRst.Fields.Item("Descr").Value), BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Error);
                    BubbleEvent = false;
                    return;
                }
            }

        }

        /// <summary>
        /// 更改状态
        /// </summary>
        /// <author>WangPeng</author>
        private void ChangeOrderStatus()
        {
            string DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "3").ToString().Trim();
            if (string.IsNullOrEmpty(DocEntry))
            {
                return;
            }
            string SQL_UpdateStatus = string.Format("UPDATE [@AVA_FF_OAOU] SET U_Status=N'S' WHERE DocEntry={0} ", DocEntry);
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            oRst.DoQuery(SQL_UpdateStatus);
            this.CurrentForm.Refresh();
        }
        /// <summary>
        /// 确认关闭主单领用
        /// </summary>
        /// <author>WangPeng</author>
        private void ConformCloseDate(ref bool BubbleEvent)
        {
            string AirOrderEntry = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "914_1").ToString().Trim();
            string CloseDate = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "37").ToString().Trim();
            SAPbouiCOM.DBDataSource dbds_OAOU = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");
            string Status_Doc = dbds_OAOU.GetValue("U_Status", dbds_OAOU.Offset).Trim();
            if (string.IsNullOrEmpty(AirOrderEntry))
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(CloseDate))/*航空公司结算日期*/
            {
                return;
            }
            if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
            {
                BubbleEvent = false;
                throw new Exception("添加[主单领用]不允许存在[航空公司结算日期].");
            }
            if (this.CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE && Status_Doc != "C")
            {
                this.CurrentForm.DataSources.UserDataSources.Item("IsClose").ValueEx = "Y";
                SBOApp.StatusBar.SetText("请确认 [航空公司结算日期] ,更新之后将关闭该主单领用.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Warning);
            }
        }

        /// <summary>
        /// 关闭主单领用、主单
        /// </summary>
        /// <author>WangPeng</author>
        private void CloseAirOrderUse()
        {
            string DocEntry = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "3").ToString().Trim();
            string AirOrderEntry = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "914_1").ToString().Trim();
            SAPbouiCOM.DBDataSource dbds_OAOU = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");
            if (string.IsNullOrEmpty(DocEntry) || string.IsNullOrEmpty(AirOrderEntry))
            {
                return;
            }
            string CloseDate = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "37").ToString().Trim();
            if (this.CurrentForm.DataSources.UserDataSources.Item("IsClose").ValueEx == "Y")
            {
                SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                string SQL_CloseAirOrder = string.Format("UPDATE [@AVA_FF_OAOU] SET U_Status=N'C' WHERE DocEntry={0} UPDATE [@AVA_FF_OAOD] SET U_Status=N'C' WHERE DocEntry={1} ", DocEntry, AirOrderEntry);
                oRst.DoQuery(SQL_CloseAirOrder);
                dbds_OAOU.SetValue("U_Status", dbds_OAOU.Offset, "C");
            }

        }

        /// <summary>
        /// 打开业务单
        /// </summary>
        /// <author>WangPeng</author>
        private void CopytoBusinessOperation()
        {
            if (this.CurrentForm.Mode != BoFormMode.fm_OK_MODE)
            {
                SBOApp.StatusBar.SetText("请先保存主单领用数据，再创建业务单.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Error);
                return;
            }
            SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");
            string Status = dbds.GetValue("U_Status", dbds.Offset).Trim();
            if (Status == "S")
            {
                this.ShowForm(B1FormTypes.ado_AVA_FF_BusinessOperation, this.CurrentForm.UniqueID);
            }
            else
            {
                SBOApp.StatusBar.SetText("创建业务单，需要先发送主单领用.", BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Error);
            }

        }

        ///// <summary>
        ///// 设置控件是否可用
        ///// </summary>
        ///// <author>WangPeng</author>
        //private void FormItemsEditState()
        //{
        //    string DocStatus = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "7").ToString().Trim();
        //    string Item_BtnCreateBP = "btn_CrtBP";
        //    string Items_Disable_PlanState = "3,7,29,61,63";
        //    string Items_Disable_SendState = "9,11,13,15,19,21,23,25";
        //    string Items_Disable_CloseState = "27,33,35,37,43,btn_Send";
        //    string Items_Disable = string.Empty;
        //    SAPbouiCOM.BoFormMode CurrentFormMode = this.CurrentForm.Mode;
        //    #region 浏览状态
        //    if (CurrentFormMode == BoFormMode.fm_OK_MODE || CurrentFormMode==BoFormMode.fm_UPDATE_MODE) //添加更新状态处理 by WangPeng 2012年10月16日 21:11:18
        //    {
        //        this.CurrentForm.Mode = BoFormMode.fm_VIEW_MODE;
        //        switch (DocStatus)
        //        {
        //            case "P":
        //                Items_Disable = string.Format("{0},{1}",Items_Disable_PlanState,Item_BtnCreateBP);
        //                break;
        //            case "S":
        //                Items_Disable = string.Format("{0},{1}", Items_Disable_PlanState, Items_Disable_SendState);
        //                break;
        //            case "C":
        //                Items_Disable = string.Format("{0},{1},{2},{3}", Items_Disable_PlanState, Items_Disable_SendState, Items_Disable_CloseState, Item_BtnCreateBP);
        //                break;
        //            default:
        //                Items_Disable = string.Format("{0},{1}", Items_Disable_PlanState, Item_BtnCreateBP);
        //                break;
        //        }
        //    }
        //    #endregion
        //    #region 添加、查找 状态
        //    if (CurrentFormMode == BoFormMode.fm_ADD_MODE)
        //    {
        //        Items_Disable = string.Format("{0},{1}", Items_Disable_PlanState, "btn_Send,btn_CrtBP");
        //    }
        //    if (CurrentFormMode == BoFormMode.fm_FIND_MODE)
        //    {
        //        Items_Disable = "btn_Send,btn_CrtBP";
        //    }
        //    #endregion
        //    List<string> List_ItemsDisable = new List<string>(Items_Disable.Split(','));
        //    foreach (SAPbouiCOM.Item item in this.CurrentForm.Items)
        //    {
        //        if (List_ItemsDisable.Contains(item.UniqueID))
        //        {
        //            item.Enabled = false;
        //        }
        //        else
        //        {
        //            item.Enabled = true;
        //        }
        //    }

        //    if (CurrentFormMode == BoFormMode.fm_OK_MODE)
        //    {
        //        this.CurrentForm.Mode = CurrentFormMode;
        //    }
        //}
        #endregion
    }

}
